class CameraClient {
    constructor() {
        this.cameras = new Map();
        this.isAIEnabled = false;
        this.currentPage = 1;
        this.itemsPerPage = 4;
        this.focusedWindow = 0;
        this.init();
    }

    async init() {
        this.bindEvents();
        this.createEmptyWindows();
        await this.loadCameras();
    }

    bindEvents() {
        document.getElementById('toggle-ai').onclick = () => {
            this.toggleAI();
        };
        document.getElementById('capture').onclick = () => {
            this.captureFrame();
        };
    }

    async loadCameras() {
        try {
            const response = await fetch('/api/cameras');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            if (data.cameras && data.cameras.length > 0) {
                const canvas = document.querySelector('.video-wrapper:nth-child(1) canvas');
                const ctx = canvas.getContext('2d');
                await this.connectCamera(0, canvas, ctx);
            }
            
            for (let i = 1; i < this.itemsPerPage; i++) {
                const canvas = document.querySelector(`.video-wrapper:nth-child(${i + 1}) canvas`);
                if (canvas) {
                    const ctx = canvas.getContext('2d');
                    this.showErrorMessage(canvas, ctx, '摄像头未连接');
                }
            }
        } catch (error) {
            const container = document.getElementById('video-container');
            container.innerHTML = `<div class="error-message">加载摄像头失败: ${error.message}</div>`;
        }
    }

    async addCamera() {
        const id = this.cameras.size;
        try {
            const response = await fetch(`/api/cameras/${id}/control`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'start'
                })
            });
            
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            if (response.ok) {
                await this.connectCamera(id, canvas, ctx);
            } else {
                const error = await response.json();
                this.showErrorMessage(canvas, ctx, error.detail || '摄像头打开失败');
            }
            
            this.cameras.set(id, { canvas });
            this.updateCameraDisplay();
        } catch (error) {
            console.error('添加摄像头失败:', error);
        }
    }

    showErrorMessage(canvas, ctx, message) {
        canvas.width = 640;
        canvas.height = 480;
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#666';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(message, canvas.width/2, canvas.height/2);
    }

    createPagination() {
        const totalPages = Math.ceil(this.cameras.size / this.itemsPerPage);
        const container = document.querySelector('.main-content');
        const paginationDiv = document.createElement('div');
        paginationDiv.className = 'pagination';
        
        const buttons = [];
        const maxVisiblePages = 5;
        let startPage = 1;
        let endPage = totalPages;
        
        if (totalPages > maxVisiblePages) {
            const halfVisible = Math.floor(maxVisiblePages / 2);
            if (this.currentPage <= halfVisible + 1) {
                endPage = maxVisiblePages;
            } else if (this.currentPage >= totalPages - halfVisible) {
                startPage = totalPages - maxVisiblePages + 1;
            } else {
                startPage = this.currentPage - halfVisible;
                endPage = this.currentPage + halfVisible;
            }
        }
        
        if (startPage > 1) {
            buttons.push(this.createPageButton(1));
            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                buttons.push(ellipsis);
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            buttons.push(this.createPageButton(i));
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                buttons.push(ellipsis);
            }
            buttons.push(this.createPageButton(totalPages));
        }
        
        buttons.forEach(btn => paginationDiv.appendChild(btn));
        container.appendChild(paginationDiv);
    }

    createPageButton(pageNum) {
        const btn = document.createElement('button');
        btn.textContent = pageNum;
        btn.onclick = () => this.changePage(pageNum);
        if (pageNum === this.currentPage) {
            btn.classList.add('active');
        }
        return btn;
    }

    changePage(page) {
        const totalPages = Math.ceil(this.cameras.size / this.itemsPerPage);
        if (page < 1 || page > totalPages) return;
        
        this.currentPage = page;
        this.updateCameraDisplay();
    }

    updateCameraDisplay() {
        const container = document.getElementById('video-container');
        container.innerHTML = '';
        
        const start = (this.currentPage - 1) * this.itemsPerPage;
        const end = start + this.itemsPerPage;
        
        Array.from(this.cameras.entries())
            .slice(start, end)
            .forEach(([id, data]) => {
                const wrapper = document.createElement('div');
                wrapper.className = 'video-wrapper';
                wrapper.appendChild(data.canvas);
                container.appendChild(wrapper);
            });
            
        const paginationDiv = document.querySelector('.pagination');
        if (paginationDiv) {
            paginationDiv.remove();
        }
        this.createPagination();
    }

    async connectCamera(id, canvas, ctx) {
        try {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const host = window.location.host;
            const ws = new WebSocket(`${protocol}//${host}/ws/camera/${id}`);
            
            ws.onopen = () => {
            };
            
            ws.onmessage = (event) => {
                const img = new Image();
                img.onload = () => {
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                };
                img.src = URL.createObjectURL(event.data);
            };
            
            ws.onerror = (error) => {
                this.showErrorMessage(canvas, ctx, '连接错误');
            };
            
            ws.onclose = () => {
                this.showErrorMessage(canvas, ctx, '连接已断开');
            };
            
            this.cameras.set(id, {ws, canvas, ctx});
        } catch (error) {
            this.showErrorMessage(canvas, ctx, '连接失败');
        }
    }

    toggleAI() {
    }

    captureFrame() {
        this.cameras.forEach((camera, id) => {
            const link = document.createElement('a');
            link.download = `camera_${id}_${Date.now()}.jpg`;
            link.href = camera.canvas.toDataURL();
            link.click();
        });
    }

    createEmptyWindows(keepFocus = false) {
        const container = document.getElementById('video-container');
        container.innerHTML = '';
        
        for (let i = 0; i < this.itemsPerPage; i++) {
            const wrapper = document.createElement('div');
            wrapper.className = 'video-wrapper';
            wrapper.id = `video-wrapper-${i}`;
            
            if (i === this.focusedWindow || (!keepFocus && i === 0)) {
                wrapper.classList.add('focused');
                this.focusedWindow = i;
            }
            
            const canvas = document.createElement('canvas');
            canvas.width = 640;
            canvas.height = 480;
            wrapper.appendChild(canvas);
            
            wrapper.addEventListener('click', (event) => {
                document.querySelectorAll('.video-wrapper').forEach(w => {
                    w.classList.remove('focused');
                });
                
                wrapper.classList.add('focused');
                this.focusedWindow = i;
            });
            
            container.appendChild(wrapper);
            const ctx = canvas.getContext('2d');
            this.showLoadingMessage(canvas, ctx);
        }
    }

    showLoadingMessage(canvas, ctx) {
        canvas.width = 640;
        canvas.height = 480;
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#666';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('正在加载视频...', canvas.width/2, canvas.height/2);
    }
}

window.onload = () => {
    window.cameraClient = new CameraClient();
}; 